
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
 */
package be.ac.ua.pats.thesisrobotica.robot.RR.sensors.listeners;

import lejos.nxt.comm.RConsole;
import lejos.util.Timer;
import lejos.util.TimerListener;

/**
 *
 * @author Admin
 */
public abstract class Listenable {
    
    protected int interval = 0;
    protected int threshold = 0;
            int          currentValue;
    int          previousValue;
    public Timer timer;

    public Listenable() {
        this(0,0);
    }

    public Listenable(int interval,int threshold) {
                this.threshold = threshold;
        timer          = new Timer(interval, new TimerListener() {
            public void timedOut() {
                stateChanged(currentValue);
                timer.stop();
                timer.start();
            }
        });
    }

    public abstract void startListening();

    public abstract void stateChanged(int value);

        public void startTimer() {
        timer.start();
    }


    public void compareThreshold(int currentValue) {
        this.currentValue = currentValue;
        if (Math.abs(currentValue - previousValue) > threshold) {
            stateChanged(currentValue);
        }
        previousValue = currentValue;
    }
    
    public int getThreshold() {
        return threshold;
    }

    public int getInterval() {
        return interval;
    }
    
    public void setThreshold(int threshold) throws IllegalArgumentException {
        if (threshold < 0) {
            throw new IllegalArgumentException("Illegal threshold:" + threshold);
        }

        this.threshold = threshold;
    }


    public void setTimeInterval(int interval) throws IllegalArgumentException {
        if (interval < 0) {
            throw new IllegalArgumentException("Illegal time interval:" + interval);
        }

        timer.setDelay(interval);
    }

}
